import request from '@/utils/request'

// AI算法相关API接口

/**
 * 获取算法列表
 * @param {Object} query 查询参数
 * @returns {Promise}
 */
export function getAlgorithmList(query = {}) {
  const params = {
    page: query.pageNum || query.page || 1,
    size: query.pageSize || query.size || 50, // 增加默认大小以显示更多算法
    status: query.status,
    type: query.type,
    search: query.name || query.search
  }

  // 移除undefined值
  Object.keys(params).forEach(key => {
    if (params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  })

  return request({
    url: '/api/v1/algorithms',
    method: 'get',
    params: params
  }).then(response => {
    console.log('算法列表API响应:', response)
    
    // 处理响应格式
    let algorithms = []
    let total = 0

    if (response.code === 200) {
      algorithms = response.rows || []
      total = response.total || algorithms.length
    } else if (Array.isArray(response)) {
      algorithms = response
      total = response.length
    } else if (response.data && Array.isArray(response.data)) {
      algorithms = response.data
      total = response.total || response.data.length
    } else if (response.rows && Array.isArray(response.rows)) {
      algorithms = response.rows
      total = response.total || response.rows.length
    }

    console.log(`解析到 ${algorithms.length} 个算法`)

    return {
      code: 200,
      msg: '查询成功',
      total: total,
      rows: algorithms.map(formatAlgorithmResponse)
    }
  }).catch(error => {
    console.error('获取算法列表失败:', error)
    throw formatErrorResponse(error)
  })
}

/**
 * 获取算法详情
 * @param {string|number} id 算法ID
 * @returns {Promise}
 */
export function getAlgorithmDetail(id) {
  return request({
    url: `/api/v1/algorithms/${id}`,
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: formatAlgorithmResponse(response)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 创建算法
 * @param {Object} data 算法数据
 * @returns {Promise}
 */
export function createAlgorithm(data) {
  const backendData = {
    name: data.name,
    type: data.type,
    version: data.version,
    description: data.description,
    config: data.config || {},
    model_path: data.modelPath || data.model_path,
    input_format: data.inputFormat || data.input_format,
    output_format: data.outputFormat || data.output_format,
    gpu_required: data.gpuRequired || false,
    memory_required: data.memoryRequired || 1024
  }

  return request({
    url: '/api/v1/algorithms',
    method: 'post',
    data: backendData
  }).then(response => {
    return {
      code: 200,
      msg: '创建成功',
      data: formatAlgorithmResponse(response)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 更新算法
 * @param {string|number} id 算法ID
 * @param {Object} data 更新数据
 * @returns {Promise}
 */
export function updateAlgorithm(id, data) {
  const backendData = {
    name: data.name,
    type: data.type,
    version: data.version,
    description: data.description,
    config: data.config,
    model_path: data.modelPath || data.model_path,
    input_format: data.inputFormat || data.input_format,
    output_format: data.outputFormat || data.output_format,
    gpu_required: data.gpuRequired,
    memory_required: data.memoryRequired,
    status: data.status
  }

  // 移除undefined值
  Object.keys(backendData).forEach(key => {
    if (backendData[key] === undefined) {
      delete backendData[key]
    }
  })

  return request({
    url: `/api/v1/algorithms/${id}`,
    method: 'put',
    data: backendData
  }).then(response => {
    return {
      code: 200,
      msg: '更新成功',
      data: formatAlgorithmResponse(response)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 删除算法
 * @param {string|number} id 算法ID
 * @returns {Promise}
 */
export function deleteAlgorithm(id) {
  return request({
    url: `/api/v1/algorithms/${id}`,
    method: 'delete'
  }).then(() => {
    return {
      code: 200,
      msg: '删除成功'
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 启动算法
 * @param {string|number} id 算法ID
 * @returns {Promise}
 */
export function startAlgorithm(id) {
  return request({
    url: `/api/v1/algorithms/${id}/start`,
    method: 'post'
  }).then(response => {
    return {
      code: 200,
      msg: '启动成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 停止算法
 * @param {string|number} id 算法ID
 * @returns {Promise}
 */
export function stopAlgorithm(id) {
  return request({
    url: `/api/v1/algorithms/${id}/stop`,
    method: 'post'
  }).then(response => {
    return {
      code: 200,
      msg: '停止成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取算法统计信息
 * @returns {Promise}
 */
export function getAlgorithmStatistics() {
  return request({
    url: '/api/v1/algorithms/statistics',
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取算法性能指标
 * @param {string|number} id 算法ID
 * @returns {Promise}
 */
export function getAlgorithmMetrics(id) {
  return request({
    url: `/api/v1/algorithms/${id}/metrics`,
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 绑定算法到摄像头
 * @param {string|number} algorithmId 算法ID
 * @param {Array} cameraIds 摄像头ID数组
 * @returns {Promise}
 */
export function bindAlgorithmToCamera(algorithmId, cameraIds) {
  return request({
    url: `/api/v1/algorithms/${algorithmId}/bind`,
    method: 'post',
    data: {
      camera_ids: cameraIds
    }
  }).then(response => {
    return {
      code: 200,
      msg: '绑定成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 解绑算法和摄像头
 * @param {string|number} algorithmId 算法ID
 * @param {Array} cameraIds 摄像头ID数组
 * @returns {Promise}
 */
export function unbindAlgorithmFromCamera(algorithmId, cameraIds) {
  return request({
    url: `/api/v1/algorithms/${algorithmId}/unbind`,
    method: 'post',
    data: {
      camera_ids: cameraIds
    }
  }).then(response => {
    return {
      code: 200,
      msg: '解绑成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 格式化算法响应数据
 * @param {Object} algorithm 后端算法数据
 * @returns {Object} 前端格式的算法数据
 */
function formatAlgorithmResponse(algorithm) {
  if (!algorithm) return null

  return {
    id: algorithm.id,
    name: algorithm.name,
    type: algorithm.type,
    version: algorithm.version,
    description: algorithm.description,
    config: algorithm.config || {},
    modelPath: algorithm.model_path,
    model_path: algorithm.model_path,
    inputFormat: algorithm.input_format,
    input_format: algorithm.input_format,
    outputFormat: algorithm.output_format,
    output_format: algorithm.output_format,
    gpuRequired: algorithm.gpu_required,
    gpu_required: algorithm.gpu_required,
    memoryRequired: algorithm.memory_required,
    memory_required: algorithm.memory_required,
    status: algorithm.status,
    createdAt: algorithm.created_at,
    created_at: algorithm.created_at,
    updatedAt: algorithm.updated_at,
    updated_at: algorithm.updated_at,
    // 运行时信息
    isRunning: algorithm.is_running || false,
    processId: algorithm.process_id,
    lastStartTime: algorithm.last_start_time,
    performance: algorithm.performance || {}
  }
}

/**
 * 格式化错误响应
 * @param {Object} error 错误对象
 * @returns {Object} 格式化的错误
 */
function formatErrorResponse(error) {
  if (error.response && error.response.data) {
    const errorData = error.response.data
    return {
      code: error.response.status || 500,
      msg: errorData.message || errorData.detail || '操作失败',
      data: null
    }
  }
  return {
    code: 500,
    msg: error.message || '网络错误',
    data: null
  }
}

/**
 * 获取摄像头绑定列表
 * @returns {Promise}
 */
export function getCameraBindings() {
  return request({
    url: '/api/v1/camera-bindings',
    method: 'get'
  }).then(response => {
    console.log('摄像头绑定API响应:', response)
    
    // 如果响应已经是正确格式，直接返回
    if (response && typeof response === 'object' && 'code' in response) {
      return response
    }
    
    // 否则包装响应
    return {
      code: 200,
      msg: '查询成功',
      data: Array.isArray(response) ? response : (response?.data || [])
    }
  }).catch(error => {
    console.error('获取摄像头绑定失败:', error)
    
    // 让错误传播到组件，而不是返回空数据
    throw formatErrorResponse(error)
  })
}

/**
 * 获取可用算法模型
 * @returns {Promise}
 */
export function getAvailableModels() {
  return request({
    url: '/api/v1/algorithms/models',
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    // 如果API调用失败，返回六大AI服务作为默认模型
    console.warn('获取算法模型失败，使用默认AI服务:', error)
    return {
      code: 200,
      msg: '查询成功',
      data: Object.keys(AI_SERVICES).map(key => ({
        model_id: key,
        name: AI_SERVICES[key],
        type: key,
        description: `${AI_SERVICES[key]}算法模型`,
        version: '1.0.0',
        status: 'active',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      }))
    }
  })
}

/**
 * 创建摄像头算法绑定
 * @param {Object} data 绑定数据
 * @returns {Promise}
 */
export function createCameraBinding(data) {
  return request({
    url: '/api/v1/camera-bindings',
    method: 'post',
    data: data
  }).then(response => {
    return {
      code: 200,
      msg: '创建成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 更新摄像头算法绑定
 * @param {string|number} cameraId 摄像头ID
 * @param {Object} data 更新数据
 * @returns {Promise}
 */
export function updateCameraBinding(cameraId, data) {
  return request({
    url: `/api/v1/camera-bindings/${cameraId}`,
    method: 'put',
    data: data
  }).then(response => {
    return {
      code: 200,
      msg: '更新成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 删除摄像头算法绑定
 * @param {string|number} cameraId 摄像头ID
 * @returns {Promise}
 */
export function deleteCameraBinding(cameraId) {
  return request({
    url: `/api/v1/camera-bindings/${cameraId}`,
    method: 'delete'
  }).then(() => {
    return {
      code: 200,
      msg: '删除成功'
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

// 导出API对象
export const aiAlgorithmApi = {
  getList: getAlgorithmList,
  getAlgorithmList: getAlgorithmList,  // 添加缺少的函数名
  getDetail: getAlgorithmDetail,
  create: createAlgorithm,
  update: updateAlgorithm,
  delete: deleteAlgorithm,
  start: startAlgorithm,
  stop: stopAlgorithm,
  getStatistics: getAlgorithmStatistics,
  getMetrics: getAlgorithmMetrics,
  bindToCamera: bindAlgorithmToCamera,
  unbindFromCamera: unbindAlgorithmFromCamera,
  getCameraBindings: getCameraBindings,
  getAvailableModels: getAvailableModels,
  createCameraBinding: createCameraBinding,
  updateCameraBinding: updateCameraBinding,
  deleteCameraBinding: deleteCameraBinding,
  getOverview: getAIServicesOverview
}

// 六大AI服务常量
export const AI_SERVICES = {
  'campus_behavior_monitoring': '校园行为监控',
  'campus_crowd_safety': '校园人群安全',
  'campus_energy_management': '校园能源管理',
  'campus_environment_hygiene': '校园环境卫生',
  'intelligent_classroom_quality': '智能课堂质量',
  'teaching_quality_assessment': '教学质量评估'
}

// 算法类型常量
export const AlgorithmTypes = {
  CAMPUS_BEHAVIOR_MONITORING: 'campus_behavior_monitoring',
  CAMPUS_CROWD_SAFETY: 'campus_crowd_safety',
  CAMPUS_ENERGY_MANAGEMENT: 'campus_energy_management',
  CAMPUS_ENVIRONMENT_HYGIENE: 'campus_environment_hygiene',
  INTELLIGENT_CLASSROOM_QUALITY: 'intelligent_classroom_quality',
  TEACHING_QUALITY_ASSESSMENT: 'teaching_quality_assessment'
}

// 算法状态常量
export const AlgorithmStatus = {
  INACTIVE: 'inactive',
  ACTIVE: 'active',
  RUNNING: 'running',
  ERROR: 'error',
  MAINTENANCE: 'maintenance'
}

/**
 * 获取AI服务概览数据
 * @returns {Promise}
 */
export function getAIServicesOverview() {
  return request({
    url: '/api/v1/ai-services/overview',
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    // 如果后端服务不可用，返回模拟数据
    return {
      code: 200,
      msg: '查询成功',
      data: {
        runningAlgorithms: 4,
        totalAlgorithms: 6,
        gpuUsage: Math.floor(Math.random() * 30) + 60,
        avgAccuracy: Math.floor(Math.random() * 10) + 90,
        alerts: Math.floor(Math.random() * 5),
        services: Object.keys(AI_SERVICES).map(key => ({
          id: key,
          name: AI_SERVICES[key],
          status: Math.random() > 0.3 ? 'running' : 'inactive',
          accuracy: Math.floor(Math.random() * 20) + 80,
          processedFrames: Math.floor(Math.random() * 10000) + 1000,
          lastUpdate: new Date().toISOString()
        }))
      }
    }
  })
}

// 向后兼容的导出别名
export const getAlgorithms = getAlgorithmList